package com.bwie.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.TbUser;
import com.bwie.service.TbUserService;
import com.bwie.mapper.TbUserMapper;
import com.bwie.utils.MD5Utils;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.LoginVo;
import com.bwie.vo.SendCodeVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author Lenovo
* @description 针对表【tb_user】的数据库操作Service实现
* @createDate 2025-07-15 09:19:55
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    TbUserMapper tbUserMapper;
    @Override
    public R login(LoginVo loginVo) {
        //手机号，邮箱登录
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbUser::getUserEmail,loginVo.getUserName()).or().eq(TbUser::getUserMobile,loginVo.getUserName());
        TbUser tbUser = tbUserMapper.selectOne(queryWrapper);
        if(tbUser==null){
            return R.ERROR(404,"用户不存在");
        }
        //密码加密
        String encrypt = MD5Utils.encrypt(loginVo.getUserPass());
        System.out.println("加密后密码:"+encrypt);
        if(!tbUser.getUserPass().equals(encrypt)){
            return R.ERROR(500,"密码错误");
        }
        //存入token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("userId", tbUser.getUserId())
                .claim("userName", tbUser.getUserName())
                .claim("nickName", tbUser.getNickName()).compact();
        String key = "token-"+tbUser.getUserId();
        stringRedisTemplate.opsForValue().set(key,token,30, TimeUnit.MINUTES);

        tbUser.setToken(token);
        return R.OK(tbUser);
    }

    @Override
    public R sendCode(String userMobile) {
//        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().eq(TbUser::getUserMobile,userMobile);
//        TbUser tbUser = tbUserMapper.selectOne(queryWrapper);
////        //在用户注册过程中，必须对输入的手机号进行唯一性检查，一个手机号只能注册一个用户
////        if(tbUser!=null){
////            return R.ERROR(500,"一个手机号只能注册一个用户");
////        }

        String code = RandomUtil.randomNumbers(4);
        System.out.println("短信验证码:"+code);
        MobileMessageUtil.sendMobileMessage(userMobile,code);
        //验证码信息存储至Redis。设置为5分钟的有效期。（2分）
        stringRedisTemplate.opsForValue().set(userMobile,code,5,TimeUnit.MINUTES);
        return R.OK(code);
    }

    @Override
    public R checkCode(String userMobile, String code) {
        String redisCode = stringRedisTemplate.opsForValue().get(userMobile);
        if(!redisCode.equals(code)){
            return R.ERROR(500,"验证码错误");
        }
        return R.OK();
    }

    @Override
    public R regLogin(TbUser tbUser) {
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbUser::getUserMobile,tbUser.getUserMobile());
        TbUser user = tbUserMapper.selectOne(queryWrapper);
        //在用户注册过程中，必须对输入的手机号进行唯一性检查，一个手机号只能注册一个用户
        if(user!=null){
            return R.ERROR(500,"一个手机号只能注册一个用户");
        }
        tbUser.setCreateTime(new Date());
        tbUserMapper.insert(tbUser);
        return R.OK();
    }

    @Override
    public R updatePass(TbUser tbUser) {
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbUser::getUserMobile,tbUser.getUserMobile());
        TbUser user = tbUserMapper.selectOne(queryWrapper);
        //修改密码需要使用encrypt进行密码加密（3分）
        String pass = MD5Utils.encrypt(user.getUserPass());
        user.setUserPass(pass);
        tbUserMapper.updateById(user);
        return R.OK();
    }


}




